﻿#include <ecal/ecal.h>
#include <ecal/msg/protobuf/client.h>

#include <iostream>

#include "protocol/echo_service.pb.h"

int main(int argc, char** argv) {
  std::string client_name = "Echo Service";
  if (argc > 1) {
    client_name = argv[1];
  }

  // 初始化 eCAL
  eCAL::Initialize(argc, argv, "Echo Client");

  // 创建客户端
  eCAL::protobuf::CServiceClient<example::EchoService> client(client_name);

  // 等待服务端连接
  while (!client.IsConnected()) {
    std::cout << "Waiting for the server to establish a connection..." << std::endl;
    eCAL::Process::SleepMS(500);
  }

  // 准备请求
  example::EchoRequest request;
  request.set_message("Hello Protobuf!");

  while (eCAL::Ok()) {
    // 发送请求
    eCAL::ServiceResponseVecT service_responses;
    if (client.Call("Echo", request, -1, &service_responses)) {
      // 处理所有响应
      for (const auto& response : service_responses) {
        switch (response.call_state) {
          case eCallState::call_state_executed: {
            example::EchoResponse echo_response;
            if (echo_response.ParseFromString(response.response)) {
              std::cout << "[Successful] Received response: " << echo_response.reply()
                        << " (success: " << echo_response.success() << ")" << std::endl;
            } else {
              std::cerr << "[Error] Response parsing failed." << std::endl;
            }
            break;
          }
          case eCallState::call_state_failed:
            std::cerr << "[Failed] Service call failed: " << response.error_msg << std::endl;
            break;
          default:
            std::cerr << "[Unknown] Unprocessed call status: " << response.call_state << std::endl;
        }
      }
    } else {
      std::cerr << "Call request failed to send." << std::endl;
    }
    
    // 等待一段时间再发送下一个请求
    eCAL::Process::SleepMS(1000);
  }
  {
    /* code */
  }

  // 清理 eCAL
  eCAL::Finalize();

  return 0;
}